<template>
  <el-container id="question" class="containermain bg-white">
    <el-aside width="50vw" class="pic-main">
      <div v-if="question" class="container question-icon">
        <div class="row col-title">
          <div class="col">
            <div class>
              {{ index + 1 }}.
              {{ question.name }}
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <div class="text-icon">
              <div class="float-start">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-lujing525" />
                </svg>
              </div>

              <div class="text-icon-title float-start">内存约束</div>
              <div class="text-icon-data float-start">
                {{
                  question.memorylimit ? Number(question.memorylimit) : 128
                }}MB
              </div>
              <span class="clearfix"></span>
            </div>
          </div>
          <div class="col">
            <div class="text-icon">
              <div class="float-start">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-jianqu1" />
                </svg>
              </div>

              <div class="text-icon-title float-start">时间约束</div>
              <div class="text-icon-data float-start">{{ question.timelimit ? Number(question.timelimit) : 200 }}ms
              </div>
              <span class="clearfix"></span>
            </div>
          </div>
        </div>
        <contextlist v-bind="{
          question, isexample: !!match.isexample,
        }"></contextlist>
      </div>
    </el-aside>
    <el-container class="border-left">
      <el-header height="54px" class="pt-2">
        <el-select size="default" :style="{ width: '106px', display: 'inline-block' }" v-model="language"
          placeholder="请选择">
          <el-option v-for="item in [
            { name: 'C', key: 'C' },
            { name: 'C++', key: 'CPP' },
            { name: 'Python', key: 'Python' },
          ]" :key="item.key" :label="item.name" :value="item.key"></el-option>
        </el-select>
        <span v-if="['C++', 'C', 'CPP'].includes(language)">
          &nbsp; &nbsp;
          <input type="checkbox" v-model="gccoptimize" /> &nbsp; O2优化</span>
        <span v-if="match.isfile">
          &nbsp; <el-checkbox disabled size="default" v-model="match.isfile">文件读写</el-checkbox>
        </span>
        <span :title="languages[language].title">&nbsp; &nbsp; &nbsp; 编译环境： {{ languages[language].text }}</span>
      </el-header>
      <el-main class="position-relative p-0 border-top">
        <MonaoEditor id="monaco" ref="editor" :value="context" v-bind="{ language }" @change="change"></MonaoEditor>
        <ConsoleQuestion ref="activeName2" v-model:textarea="textarea"
          v-bind="{ ouput, drawer, runcode, range: question.range, loading }"></ConsoleQuestion>
      </el-main>
    </el-container>
    <div class="pa foter row">
      <div class="col-7">
        <slot></slot>
      </div>
      <div class="col-5 text-right">
        <el-button class="btn-11" @click="drawer = !drawer">控制台</el-button>
      </div>
    </div>
  </el-container>
</template>

<script setup lang='ts'>
import { ElMessage } from "element-plus";
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
import { Socket } from "socket.io-client";
import {
  computed,
  ComputedRef,
  inject,
  nextTick,
  onMounted,
  onUnmounted,
  reactive,
  ref,
  toRaw,
  toRefs,
  watch,
} from "vue";
import { useStore } from "vuex";
import { Apimatchuserquestion, jilurizhi } from "../../../api";
import MonaoEditor from "../../../components/MonaoEditor.vue";
import ConsoleQuestion from "../../../components/watchquestion/ConsoleQuestion.vue";
import contextlist from '../../../components/watchquestion/contextlist.vue';
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { languages } from "../../data/data";
type P = {
  question: Studycodemodel.Imatchquestion
  userdata: Record<string | number, any>
  setuserdata: Function
  index: number
  match: Studycodemodel.Iactivity
  matchuser?: Apimatchuserquestion
}



const prop = defineProps<P>()
const store = useStore(Storekey);
const { question, userdata, index, match } = toRefs(prop);
const gccoptimize = ref<boolean>(prop.match.iso2 || true)

const drawer = ref(false);

const textarea = ref("");
const language = ref<keyof Studycodemodel.Ilang>('CPP');
const context = ref("");
const loading = ref(false);
const ouput = reactive({
  t: 0,
  stdout: "",
  stderr: "",
});

onMounted(() => {
  const app = document.querySelector("html");
  if (app) {
    app.style.overflowY = "hidden";
  }
  start();
});

onUnmounted(() => {
  document.title = "noipcode";
  console.log("onUnmounted")
  prop.setuserdata(question.value.ID, {
    context: context.value,
    language: language.value,
    gccoptimize: gccoptimize.value,
  });
});

watch(
  () => question?.value.ID,
  (_v, ol) => {
    prop.setuserdata(ol, {
      context: context.value,
      language: language.value,
      gccoptimize: gccoptimize.value,
    });
    start();
  }
);


async function start() {
  nextTick(() => {
    const { name, ID } = toRaw(question.value);
    document.title = name || "noipcode";
    if (ID && userdata?.value) {
      context.value = userdata.value[ID]?.context;
      gccoptimize.value = userdata.value[ID]?.gccoptimize === undefined ? gccoptimize.value : userdata.value[ID]?.gccoptimize
      if (userdata.value[ID]?.language) {
        language.value = userdata.value[ID]?.language
      } else {
        language.value = prop.match.language || 'CPP'
      }
    } else {
      context.value = "";
    }
  });
}
const _runcode = inject("runcode", () => true);
const getuser = computed<Studycodemodel.Iuser>(() => {
  return store.getters.getuser;
});
const getcode = inject<
  ComputedRef<{
    data?: Studycodemodel.Iuserquestioninfo[];
    run?: true;
    error?: number;
    msg?: string;
  }>
>("getcode");

watch(
  () => getcode?.value,
  (d) => {
    if (d) {
      const { data, run, error, msg = "" } = d;
      if (error) {
        ElMessage.error("运行失败");
        ouput.stdout = "";
        ouput.t = NaN;
        ouput.stderr = msg;
      } else {
        ElMessage.success("运行成功");
        if (run && data) {
          Object.assign(ouput, data[0]);
        }
      }

      loading.value = false;
    }
  }
);

const activeName2 = ref()


watch(() => loading.value, (v) => {
  if (v) {
    activeName2.value.activeName2 = "second";
  }
});

async function runcode(run?: boolean) {
  _runcode();

  if (!context.value || context.value?.length < 20) {
    ElMessage.error("代码内容太少");
    return;
  }

  if (!run && !textarea.value) {
    ElMessage.error("请填入测试用例");
    drawer.value = true;
    return;
  }

  loading.value = true;
  drawer.value = true;
  const scoket: Socket | undefined =
    store.state.socket;
  if (!question.value.ID) return;
  const arr: [string, any][] = [];

  arr[0] = ["_method_", "runcode"];
  arr[1] = ["type", "scoket"];
  arr[2] = ["questionid", String(question.value.ID)];
  arr[3] = ["questionname", String(question.value.name)];
  arr[4] = ["ismatch", true];
  arr[5] = ["matchid", match.value?.ID];
  arr[6] = ["matchname", match.value?.name];
  jilurizhi(arr);
  scoket.emit("runcode", {
    context: context.value,
    language: language.value,
    textarea: textarea.value,
    questionid: question.value.ID,
    userid: getuser.value.ID,
    run,
    gccoptimize: gccoptimize.value ? '-O2' : undefined,
    // 比赛的运行测试和提交代码 需要加上是否文件读写
    isfile: match.value.isfile || false,
  });
}

// 有问题？？？？？？
function change(v?: string, e?: monaco.editor.IModelContentChangedEvent) {
  if (e && v) {
    context.value = v;
  }
}

defineExpose({
  context,
  language,
  gccoptimize,
})

</script>
<style scoped>
#monaco {
  height: 80vh;
  overflow: hidden;
}

.slide-fade-enter-active {
  transition: all 0.3s ease;
}

.slide-fade-leave-active {
  transition: all 0.3s;
}

.marg {
  margin: 20px auto;
  padding: 3px;
}

.slide-fade-enter,
.slide-fade-leave-to {
  transform: translateX(10px);
  opacity: 0;
}

.el-icon-star-on {
  color: chartreuse;
  font-size: 24px;
}

.text-h {
  font-size: 16px;
  font-weight: 600;
  color: var(--color-303133);
}

.m-10 {
  margin-top: 26px;
  margin-bottom: 10px;
}

.pa {
  padding-top: 0;
  padding-bottom: 0;
  padding-left: 0;
  padding-right: 0;
}

.foter {
  padding-top: 10px;
  height: 60px;
  position: fixed;
  bottom: 0;
  width: 100vw;
  background-color: #fff;
  border-top: 1px solid #dfdfdf;
  margin-left: 0px;
  margin-right: 0px;
}

.tabs {
  margin: 25px;
}

.Drawer {
  position: absolute;
  bottom: 0px;
  width: 100%;
  background-color: #fff;
  border-top: 1px solid #dfdfdf;
  min-height: 300px;
}

.textarea {
  position: relative;
  padding: 5px;
  border: 1px solid #eeeeee;
}

.textarea {
  width: 100%;
  height: 150px;
}

.el-icon-video-play {
  width: 50px;
  height: 50px;
  font-size: 48px;
  display: block;
  position: absolute;
  right: -15px;
  bottom: 115px;
  z-index: 989;
  cursor: pointer;
  transition: all 0.5s;
}

.el-icon-video-play:hover {
  color: blueviolet;
}

#question.btn-outline-primary:hover {
  background-color: #409eff;
}

.pic-main {
  max-height: 85vh;
  overflow-y: auto;
  overflow-x: hidden;
  padding-bottom: 100px;
}

.pic-main::-webkit-scrollbar {
  width: 3px;
  height: 1px;
}

.pic-main::-webkit-scrollbar-thumb {
  border-radius: 3px;
  box-shadow: inset 0 0 5px rgba(0, 0, 255, 0.3);
  background: #535353;
}

.pic-main::-webkit-scrollbar-track {
  box-shadow: inset 0 0 5px rgba(0, 0, 255, 0.3);
  border-radius: 3px;
  background: #ededed;
}

.span-h {
  display: inline-block;
  margin-left: 35px;
}

.button {
  padding: 2px 8px;
  font-size: 12px;
  margin: 10px 5px;
}

.border-dark {
  color: #32325d;
}

.btn-login {
  background-color: var(--color-50);
  color: #fff;
}

.btn-login:hover {
  background-color: rgb(11, 21, 38);
  color: #fff;
}

h5 {
  font-size: 18px;
}

.question-icon {
  padding-top: 5px;
}

.question-icon .icon-z {
  height: 145px;
  width: 145px;
  display: inline-block;
  margin-right: 10px;
}

.question-icon .icon-t {
  display: inline-block;
  height: 145px;
  width: 125px;
}

.question-icon .card {
  height: 145px;
}

.question-icon .card .card-body {
  padding: 0.25rem;
}

.question-icon .card-img-top {
  height: 52px;
  width: 52px;
  margin: 15px auto;
}

.cE3F1FF {
  background-color: #e3f1ff;
}

.col-title {
  font-size: var(--size-t1);
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: var(--color-303133);
  margin-top: 20px;
  margin-bottom: 22px;
  line-height: 32px;
  height: 32px;
}
</style>

<style>
#question .el-tabs__header {
  padding: 0;
}

.Drawer .el-tabs__content {
  margin: 5px;
}

#question button:focus {
  outline: none;
}
</style>